package ArrayList;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Author:  LiuTao
 * Version: 1.0
 * Date:    2023-12-08  16:58
 */
public class MyArrayList implements IList{
    private int[] elems;
    private int usedSize;
    private static final int DEFAULT_SIZE = 10;
    public MyArrayList() {
        elems = new int[DEFAULT_SIZE];
    }

    public MyArrayList(int capacity) {
        elems = new int[capacity];
    }
    @Override
    public void add(int data) {
        checkCapacity();
        elems[usedSize] = data;
        usedSize++;
    }
    private void checkCapacity() {
        if(isFull()) {
            elems = Arrays.copyOf(elems,elems.length*2);
        }
    }

    private boolean isFull() {
        return usedSize == elems.length;
    }
    @Override
    public void add(int pos, int data) {
        for(int i = usedSize-1; i >= pos; i--) {
            elems[i + 1] = elems[i];
        }
        elems[pos] = data;
        usedSize++;
    }

    @Override
    public boolean contains(int toFind) {
        if(isEmpty()) {
            return false;
        }
        for(int i = 0; i < usedSize; i++) {
            if(elems[i] == toFind) {
                return true;
            }
        }
        return false;
    }

    private boolean isEmpty() {
        if(usedSize == 0) {
            return true;
        }
        return false;
    }

    @Override
    public int indexOf(int toFind) {
        for(int i = 0; i < usedSize; i++) {
            if(elems[i] == toFind) {
                return usedSize;
            }
        }
        return -1;
    }

    @Override
    public int get(int pos) {
        for(int i = 0; i < usedSize; i++) {
            if(elems[i] == pos) {
                return elems[i];
            }
        }
        return -1;
    }

    @Override
    public void set(int pos, int value) {
        for(int i = 0; i < usedSize; i++) {
            if(i == pos) {
                elems[i] = value;
            }
        }
    }

    @Override
    public void remove(int toRemove) {
        for(int i = 0; i < usedSize; i++) {
            if(elems[i] == toRemove) {
                for(int j = i; j < usedSize; j++) {
                    elems[j] = elems[j+1];
                }
                usedSize--;
                return;
            }
        }
    }

    @Override
    public int size() {
        return usedSize;
    }

    @Override
    public void clear() {
        this.usedSize = 0;
    }

    @Override
    public void display() {
        for(int i = 0; i < this.usedSize; i++) {
            System.out.print(this.elems[i] + " ");
        }
        System.out.println();
    }
}
